define(function(require, exports, module) {
    'use strict';
    
    
    var rk = require('rk');
    require('core/widgets/input/checkbox/widget');
    var scheduleUtil = require('oa/js/schedule/asset/utils/scheduleUtil');

    $.widget('rk.calEventTypeSelCtrl', {
            val: null,
            ulObj: null,
            dropdownBtn: null,
            _create: function(){
                var me = this;
                var elem = me.element;
                me.dropDivObj = elem.find('div.drop_div');
                me.dropdownBtn = elem.find('a.type_title');
                me.dropdownBtn.bind('click', function (){
                    if(!me.loaded){
                        scheduleUtil.fetchColorList(function(data){
                            me.scheduleColors = data;
                            me.popup();
                            me.loaded = true;
                        });
                    }else{
                        if(!me.dropDivObj.is(':visible')){
                            me.popup();
                        }else{
                            me._close();
                        }                    
                    }                
                });
                //me.setTypeId('0');    
            },
            scheduleColors: null,
            loaded:false,
            inited: false,
            _getColorArray: function(oldArray){
                var newArray = [];
                var default_color;
                for(var i = 0, len = oldArray.length; i < len; i++){
                    var color = oldArray[i];
                    color = $.extend({}, color);
                    if(color.color != 'schedule_none'){
                        newArray.push(color);
                    }else{
                        default_color = color;
                    }
                }
                if(default_color)
                newArray.push(default_color);
                return newArray;
            },
            popup: function (){
                var me = this;
                var elem = me.element;
                if(me.inited){
                    me._show();
                    return;
                }
                if(!me.scheduleColors  || !me.scheduleColors.length){
                    var tip = $(elem).qtip({
                        content: rk.i18n('SCHEDULE_1'),
                        overwrite: true,
                        show:true,
                        hide: {
                            event: 'mouseleave'
                        }
                    });
                    return;
                }
                var colorArray = me.scheduleColors;
                colorArray = me._getColorArray(colorArray);
                me._show();
                var listhtml = '<ul>';
                for(var i = 0, len = colorArray.length; i < len; i++){
                    var def = colorArray[i];
                    if(def.dummyType == 32){
                        continue;
                    }
                    listhtml = listhtml + '<li><a href="javascript:void(0)">'+
                                                '<input id="test_checkbox'+i+'" type="checkbox" '+
                                                ((!me.valueIsDirty && def.id==='0') ?'checked':'')+' '+
                                                (me.val===def.id ?'checked':'')+
                                                ' value="'+def.id+'" value-color="'+def.color+'" checked-css="'+def.color+'_check" unchecked-css="'+def.color+'_normal"/>'+
                                                '<span>'+def.name+'</span></a></li>';
                }
                listhtml = listhtml + '</ul>';
                me.dropDivObj.html(listhtml);
                me.ulObj = me.dropDivObj.find('ul');
                
                $(me.ulObj).find('input[type="checkbox"]').rkCheckbox({
                        noClick: true,//no click listening
                        ifChanged: function(){},
                        ifClicked: function(){},
                        ifUnchecked: function(){
                            if(me.ulObj.find('input:checked').size()==0){
                                me.val = null;
                                me._resetTitle();
                            }                        
                        },
                        ifChecked: function(){
                            var checkbox = $(this);
                            var val = checkbox.attr('value');
                            window.setTimeout(function(){
                                me._unselectOthers(val);
                            }, 5);
                            // var text = checkbox.siblings('span').text();      
                            // var color =  checkbox.attr('value-color');
                            // me._updateTitle(text, color);
                            me._updateTitleById(val);
                            me.val = val;                        
                        }
                });
                $(me.dropDivObj).bind('mouseleave', function(){
                    // me.popupTimerHandle = window.setTimeout(function(){                    
                    //     me._close();
                    // }, 200);                
                }).bind('mousemove', function(){
                    window.clearTimeout(me.popupTimerHandle);
                });
                $(me.dropDivObj).on('click', 'a', function(e){
                    var checkbox = $(this).find('input:checkbox');
                    checkbox.rkCheckbox('toggle');
                    me._close();
                    //$(this).find('input:checkbox').rkCheckbox('check');//WARN: will cause dead loop if bind both <li> and <li.checkbox>
                });
                //
                me.dropdownBtn.bind('mouseup', function(){
                    window.clearTimeout(me.popupTimerHandle);
                });
                me.dropDivObj.bind('mouseup', function(){
                    window.clearTimeout(me.popupTimerHandle);
                });
                $(document.body).bind('mousedown', function(){
                    me.popupTimerHandle = window.setTimeout(function(){ me._close(); }, 150);
                });
                me.inited = true;
            },
            popupTimerHandle: null,
            _show: function(){
                var me = this;
                window.clearTimeout(me.popupTimerHandle);
                me.dropDivObj.css('top',0).show();
            },
            _close: function (){
                //return;
                var me = this;
                if($(me.dropDivObj).is(':visible'))
                $(me.dropDivObj).hide( 'blind', {}, 100, function(){} );
            },
            _select: function(val){
                var me = this;
                var target = me.ulObj.find('input[value="'+val+'"]');
                target.rkCheckbox('check'); 
            },
            _unselect: function(){
                var me = this;
                me.ulObj.find('input:checked').rkCheckbox('uncheck');
            },
            _unselectOthers: function (val){
                var me = this;
                me.ulObj.find('input:checkbox').not('[value="'+val+'"]').each(function (){
                    var ck = $(this);
                    if(ck.prev().hasClass('rkCheckbox') && ck.rkCheckbox('isChecked'))ck.rkCheckbox('uncheck');
                });
            },
            _resetTitle: function(){
                var me = this;
                me.element.find('.null-text').show();
                me.element.find('[data-is="colorIndicator"]').hide();
                me.element.find('.selected-color').remove();
                me._findTextDiv().text(rk.i18n('SCHEDULE_SELECT_TYPE_INPUT_CONTENT'));
            },
            _updateTitleById: function (id){
                var me = this;
                if(!me.scheduleColors)return;
                if(!me.scheduleColors  || !me.scheduleColors.length) return;
                var colors = me.scheduleColors;
                for(var i = 0, len = colors.length; i<len; i++){
                    var color = colors[i];
                    if(color.id == id){
                        var text = color.name;
                        var color =  color.color;
                        me._updateTitle(text, color);
                    }
                }
            },
            _updateTitle: function(text, color){
                var me = this;
                me.dropdownBtn.find('.null-text').hide();
                me.element.find('[data-is="colorIndicator"]').removeClass().addClass(color+'_20').show();
                me.element.find('.type_title').find('.selected-color').css('background-color', '#'+color);
                //alert(me.element.attr('class'));
                return;
                me._findTextDiv().val(text);
            },
            _findTextDiv: function(){
                var me = this;
                return me.element.parent().prev().find('input');
                //return me.element.parent().prev('.schedule_type').find('.type_content');
            },
            getTypeId: function(){
                var me = this;
                return me.val;
            },
            valueIsDirty: false,
            setTypeId: function(id){
                var me = this;
                me.val = id+'';
                if(!me.loaded){//no popup yet
                    scheduleUtil.fetchColorList(function(data){
                                me.scheduleColors = data;
                                me.loaded = true;
                                me._updateTitleById(id);
                    });
                }else{
                    me._select(id);
                }
                me.valueIsDirty = true;
            }
            
    });
});